// 初始化地图
let map = L.map('map').setView([39.9042, 116.4074], 12);
let baseLayer = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);

// 保存当前图层，用于清除
let currentLayers = [];

// API 服务器 URL
const API_URL = 'http://localhost:3000/api';

// 服务器状态检查
checkServerStatus();

// 清除所有当前图层的函数
function clearLayers() {
    currentLayers.forEach(layer => map.removeLayer(layer));
    currentLayers = [];
}

// 检查服务器状态
async function checkServerStatus() {
    try {
        const response = await fetch(`${API_URL}/health`);
        const data = await response.json();
        
        if (data.status === 'ok') {
            document.getElementById('server-status').textContent = '在线';
            document.getElementById('server-status').className = 'status online';
        } else {
            throw new Error('服务器状态异常');
        }
    } catch (error) {
        document.getElementById('server-status').textContent = '离线';
        document.getElementById('server-status').className = 'status offline';
        console.error('服务器连接失败:', error);
    }
}

// 面板切换逻辑
document.querySelectorAll('.api-btn').forEach(btn => {
    btn.addEventListener('click', () => {
        // 隐藏主菜单
        document.getElementById('main-menu').classList.add('hidden-panel');
        
        // 显示选中的面板
        const panelId = btn.getAttribute('data-panel');
        document.getElementById(panelId).classList.add('active-panel');
        document.getElementById(panelId).classList.remove('hidden-panel');
        
        // 初始化对应面板的地图
        setupMapForPanel(panelId);
    });
});

// 返回按钮逻辑
document.querySelectorAll('.back-btn').forEach(btn => {
    btn.addEventListener('click', () => {
        // 隐藏所有面板
        document.querySelectorAll('#menu > div:not(#main-menu)').forEach(panel => {
            panel.classList.add('hidden-panel');
            panel.classList.remove('active-panel');
        });
        
        // 显示主菜单
        document.getElementById('main-menu').classList.remove('hidden-panel');
        
        // 清除地图上的图层
        clearLayers();
        
        // 重置响应区域
        document.querySelectorAll('#response').forEach(el => {
            el.textContent = '';
        });
    });
});

// 根据不同面板设置地图
function setupMapForPanel(panelId) {
    clearLayers();
    
    switch(panelId) {
        case 'distance-panel':
            setupDistanceMap();
            break;
        case 'point-in-polygon-panel':
            setupPointInPolygonMap();
            break;
        case 'buffer-panel':
            setupBufferMap();
            break;
        case 'nearest-panel':
            setupNearestMap();
            break;
        case 'simplify-panel':
            setupSimplifyMap();
            break;
        case 'cluster-panel':
            setupClusterMap();
            break;
        case 'union-panel':
            setupUnionMap();
            break;
    }
}

// 显示 API 响应
function showResponse(panelId, data) {
    const responseElement = document.querySelector(`#${panelId} #response`);
    responseElement.textContent = JSON.stringify(data, null, 2);
}

// 处理 API 错误
function handleApiError(panelId, error) {
    console.error('API 请求错误:', error);
    const responseElement = document.querySelector(`#${panelId} #response`);
    responseElement.textContent = `错误: ${error.message || '服务器连接失败'}`;
    responseElement.style.color = '#c62828';
}

// 1. 距离计算地图设置
function setupDistanceMap() {
    // 获取表单中的初始坐标
    const lng1 = parseFloat(document.getElementById('point1-lng').value);
    const lat1 = parseFloat(document.getElementById('point1-lat').value);
    const lng2 = parseFloat(document.getElementById('point2-lng').value);
    const lat2 = parseFloat(document.getElementById('point2-lat').value);
    
    // 添加两个点到地图上
    const marker1 = L.marker([lat1, lng1], {
        draggable: true,
        title: "起点"
    }).bindPopup('起点').addTo(map);
    
    const marker2 = L.marker([lat2, lng2], {
        draggable: true,
        title: "终点"
    }).bindPopup('终点').addTo(map);
    
    // 画线连接两点
    const line = L.polyline([[lat1, lng1], [lat2, lng2]], {
        color: 'blue'
    }).addTo(map);
    
    // 保存图层
    currentLayers.push(marker1, marker2, line);
    
    // 当点被拖动时更新线和表单值
    marker1.on('drag', function(e) {
        const latlng = e.target.getLatLng();
        line.setLatLngs([[latlng.lat, latlng.lng], [marker2.getLatLng().lat, marker2.getLatLng().lng]]);
        document.getElementById('point1-lng').value = latlng.lng.toFixed(4);
        document.getElementById('point1-lat').value = latlng.lat.toFixed(4);
    });
    
    marker2.on('drag', function(e) {
        const latlng = e.target.getLatLng();
        line.setLatLngs([[marker1.getLatLng().lat, marker1.getLatLng().lng], [latlng.lat, latlng.lng]]);
        document.getElementById('point2-lng').value = latlng.lng.toFixed(4);
        document.getElementById('point2-lat').value = latlng.lat.toFixed(4);
    });
    
    // 调整地图视图
    map.fitBounds([
        [lat1, lng1],
        [lat2, lng2]
    ], { padding: [50, 50] });
    
    // 表单提交事件
    document.getElementById('distance-form').addEventListener('submit', async function(e) {
        e.preventDefault();
        
        const point1 = [
            parseFloat(document.getElementById('point1-lng').value),
            parseFloat(document.getElementById('point1-lat').value)
        ];
        
        const point2 = [
            parseFloat(document.getElementById('point2-lng').value),
            parseFloat(document.getElementById('point2-lat').value)
        ];
        
        const units = document.getElementById('distance-units').value;
        
        try {
            const response = await fetch(`${API_URL}/distance`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ point1, point2, units })
            });
            
            if (!response.ok) {
                throw new Error(`API 请求失败: ${response.status}`);
            }
            
            const data = await response.json();
            showResponse('distance-panel', data);
            
            // 更新地图上的线条
            line.setLatLngs([
                [point1[1], point1[0]],
                [point2[1], point2[0]]
            ]);
            
            // 更新地图上的点标记
            marker1.setLatLng([point1[1], point1[0]]);
            marker2.setLatLng([point2[1], point2[0]]);
            
            // 在线段中点显示距离信息
            const midpoint = turf.midpoint(point1, point2);
            const distanceLabel = L.marker([midpoint.geometry.coordinates[1], midpoint.geometry.coordinates[0]], {
                icon: L.divIcon({
                    className: 'distance-label',
                    html: `<div style="background:white;padding:5px;border-radius:5px;border:1px solid #777">${data.distance.toFixed(2)} ${units}</div>`,
                })
            }).addTo(map);
            
            currentLayers.push(distanceLabel);
            
        } catch (error) {
            handleApiError('distance-panel', error);
        }
    });
}

// 2. 点在多边形内判断地图设置
let testPolygon;
function setupPointInPolygonMap() {
    // 获取表单中的初始坐标
    const lng = parseFloat(document.getElementById('point-lng').value);
    const lat = parseFloat(document.getElementById('point-lat').value);
    
    // 添加点到地图上
    const marker = L.marker([lat, lng], {
        draggable: true,
        title: "测试点"
    }).bindPopup('测试点').addTo(map);
    
    currentLayers.push(marker);
    
    // 创建一个示例多边形
    const polygonCoords = [
        [39.9150, 116.3800],
        [39.9150, 116.4100],
        [39.9000, 116.4100],
        [39.9000, 116.3800],
        [39.9150, 116.3800]
    ];
    
    testPolygon = L.polygon(polygonCoords, {
        color: 'blue',
        fillOpacity: 0.3
    }).addTo(map);
    
    currentLayers.push(testPolygon);
    
    // 当点被拖动时更新表单值
    marker.on('drag', function(e) {
        const latlng = e.target.getLatLng();
        document.getElementById('point-lng').value = latlng.lng.toFixed(4);
        document.getElementById('point-lat').value = latlng.lat.toFixed(4);
    });
    
    // 调整地图视图
    map.fitBounds(polygonCoords, { padding: [50, 50] });
    
    // 表单提交事件
    document.getElementById('point-in-polygon-form').addEventListener('submit', async function(e) {
        e.preventDefault();
        
        const point = [
            parseFloat(document.getElementById('point-lng').value),
            parseFloat(document.getElementById('point-lat').value)
        ];
        
        // 获取多边形坐标，Leaflet 和 Turf.js 的坐标顺序不同，需要转换
        const polygonLatLngs = testPolygon.getLatLngs()[0];
        const polygon = [
            polygonLatLngs.map(latlng => [latlng.lng, latlng.lat])
        ];
        
        try {
            const response = await fetch(`${API_URL}/pointInPolygon`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ point, polygon })
            });
            
            if (!response.ok) {
                throw new Error(`API 请求失败: ${response.status}`);
            }
            
            const data = await response.json();
            showResponse('point-in-polygon-panel', data);
            
            // 更新点的样式以反映结果
            marker.setIcon(L.icon({
                iconUrl: data.isInside ? 
                    'https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-green.png' : 
                    'https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-red.png',
                iconSize: [25, 41],
                iconAnchor: [12, 41]
            }));
            
            marker.bindPopup(data.isInside ? '点在多边形内' : '点不在多边形内').openPopup();
            
        } catch (error) {
            handleApiError('point-in-polygon-panel', error);
        }
    });
}

// 3. 缓冲区地图设置
function setupBufferMap() {
    // 获取表单中的初始坐标
    const lng = parseFloat(document.getElementById('buffer-point-lng').value);
    const lat = parseFloat(document.getElementById('buffer-point-lat').value);
    const radius = parseFloat(document.getElementById('buffer-radius').value);
    
    // 添加点到地图上
    const marker = L.marker([lat, lng], {
        draggable: true,
        title: "中心点"
    }).bindPopup('缓冲区中心点').addTo(map);
    
    currentLayers.push(marker);
    
    // 当点被拖动时更新表单值
    marker.on('drag', function(e) {
        const latlng = e.target.getLatLng();
        document.getElementById('buffer-point-lng').value = latlng.lng.toFixed(4);
        document.getElementById('buffer-point-lat').value = latlng.lat.toFixed(4);
    });
    
    // 调整地图视图
    map.setView([lat, lng], 13);
    
    // 表单提交事件
    document.getElementById('buffer-form').addEventListener('submit', async function(e) {
        e.preventDefault();
        
        const pointLng = parseFloat(document.getElementById('buffer-point-lng').value);
        const pointLat = parseFloat(document.getElementById('buffer-point-lat').value);
        const radius = parseFloat(document.getElementById('buffer-radius').value);
        const units = document.getElementById('buffer-units').value;
        
        // 创建点 GeoJSON
        const pointGeoJson = {
            type: 'Feature',
            geometry: {
                type: 'Point',
                coordinates: [pointLng, pointLat]
            },
            properties: {}
        };
        
        try {
            const response = await fetch(`${API_URL}/buffer`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ 
                    geojson: pointGeoJson,
                    radius: radius,
                    units: units
                })
            });
            
            if (!response.ok) {
                throw new Error(`API 请求失败: ${response.status}`);
            }
            
            const data = await response.json();
            showResponse('buffer-panel', data);
            
            // 删除之前的缓冲区
            currentLayers.forEach(layer => {
                if (layer instanceof L.Polygon) {
                    map.removeLayer(layer);
                }
            });
            
            // 显示新的缓冲区
            if (data.bufferedGeojson && data.bufferedGeojson.geometry) {
                const bufferCoords = data.bufferedGeojson.geometry.coordinates[0].map(coord => [coord[1], coord[0]]);
                
                const bufferPolygon = L.polygon(bufferCoords, {
                    color: '#ff9800',
                    fillOpacity: 0.3
                }).bindPopup(`半径 ${radius} ${units} 的缓冲区`).addTo(map);
                
                currentLayers.push(bufferPolygon);
                
                // 调整地图视图
                map.fitBounds(bufferPolygon.getBounds(), { padding: [50, 50] });
            }
        } catch (error) {
            handleApiError('buffer-panel', error);
        }
    });
}

// 4. 最近点查找地图设置
let pointsCollection = [];
function setupNearestMap() {
    // 获取表单中的初始坐标
    const lng = parseFloat(document.getElementById('target-lng').value);
    const lat = parseFloat(document.getElementById('target-lat').value);
    
    // 添加目标点到地图上
    const targetMarker = L.marker([lat, lng], {
        draggable: true,
        title: "目标点"
    }).bindPopup('目标点').addTo(map);
    
    currentLayers.push(targetMarker);
    
    // 生成一些随机点
    pointsCollection = [];
    for (let i = 0; i < 10; i++) {
        // 在目标点周围随机生成点
        const offsetLng = (Math.random() - 0.5) * 0.05;
        const offsetLat = (Math.random() - 0.5) * 0.05;
        
        const pointLng = lng + offsetLng;
        const pointLat = lat + offsetLat;
        
        pointsCollection.push({
            coordinates: [pointLng, pointLat],
            properties: { name: `点 ${i+1}` }
        });
        
        // 添加到地图
        const marker = L.circleMarker([pointLat, pointLng], {
            radius: 5,
            fillColor: '#3388ff',
            color: '#3388ff',
            weight: 1,
            opacity: 1,
            fillOpacity: 0.7
        }).bindPopup(`点 ${i+1}`).addTo(map);
        
        currentLayers.push(marker);
    }
    
    // 当目标点被拖动时更新表单值
    targetMarker.on('drag', function(e) {
        const latlng = e.target.getLatLng();
        document.getElementById('target-lng').value = latlng.lng.toFixed(4);
        document.getElementById('target-lat').value = latlng.lat.toFixed(4);
    });
    
    // 调整地图视图
    map.fitBounds([
        [lat - 0.03, lng - 0.03],
        [lat + 0.03, lng + 0.03]
    ]);
    
    // 表单提交事件
    document.getElementById('nearest-form').addEventListener('submit', async function(e) {
        e.preventDefault();
        
        const targetLng = parseFloat(document.getElementById('target-lng').value);
        const targetLat = parseFloat(document.getElementById('target-lat').value);
        
        try {
            const response = await fetch(`${API_URL}/nearest`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ 
                    targetPoint: [targetLng, targetLat],
                    points: pointsCollection
                })
            });
            
            if (!response.ok) {
                throw new Error(`API 请求失败: ${response.status}`);
            }
            
            const data = await response.json();
            showResponse('nearest-panel', data);
            
            // 重置所有点的样式
            currentLayers.forEach(layer => {
                if (layer instanceof L.CircleMarker) {
                    layer.setStyle({
                        fillColor: '#3388ff',
                        color: '#3388ff'
                    });
                }
            });
            
            // 移除之前的连线
            currentLayers = currentLayers.filter(layer => {
                if (layer instanceof L.Polyline && !(layer instanceof L.Polygon)) {
                    map.removeLayer(layer);
                    return false;
                }
                return true;
            });
            
            // 高亮显示最近的点
            if (data.nearest) {
                const nearestCoord = data.nearest.geometry.coordinates;
                
                // 查找对应的圆形标记并更改样式
                currentLayers.forEach(layer => {
                    if (layer instanceof L.CircleMarker) {
                        const latlng = layer.getLatLng();
                        if (Math.abs(latlng.lng - nearestCoord[0]) < 0.0001 && 
                            Math.abs(latlng.lat - nearestCoord[1]) < 0.0001) {
                            layer.setStyle({
                                fillColor: '#f44336',
                                color: '#f44336',
                                radius: 8
                            });
                            layer.bindPopup(`${data.nearest.properties.name} (最近点)`).openPopup();
                        }
                    }
                });
                
                // 添加连线
                const line = L.polyline([
                    [targetLat, targetLng],
                    [nearestCoord[1], nearestCoord[0]]
                ], {
                    color: '#f44336',
                    weight: 2,
                    dashArray: '5, 5'
                }).addTo(map);
                
                currentLayers.push(line);
                
                // 计算距离
                const distance = turf.distance(
                    [targetLng, targetLat],
                    nearestCoord,
                    { units: 'kilometers' }
                );
                
                // 在连线中点显示距离
                const midpoint = turf.midpoint(
                    [targetLng, targetLat],
                    nearestCoord
                );
                
                const distanceLabel = L.marker([midpoint.geometry.coordinates[1], midpoint.geometry.coordinates[0]], {
                    icon: L.divIcon({
                        className: 'distance-label',
                        html: `<div style="background:white;padding:5px;border-radius:5px;border:1px solid #777">${distance.toFixed(3)} 公里</div>`,
                    })
                }).addTo(map);
                
                currentLayers.push(distanceLabel);
            }
            
        } catch (error) {
            handleApiError('nearest-panel', error);
        }
    });
}

// 5. 线简化地图设置
let complexLine;
function setupSimplifyMap() {
    // 创建一条复杂的线路
    const complexCoords = [
        [39.9200, 116.3800],
        [39.9190, 116.3830],
        [39.9195, 116.3850],
        [39.9180, 116.3870],
        [39.9185, 116.3890],
        [39.9170, 116.3910],
        [39.9175, 116.3920],
        [39.9165, 116.3940],
        [39.9170, 116.3960],
        [39.9160, 116.3980],
        [39.9165, 116.3990],
        [39.9155, 116.4010],
        [39.9160, 116.4030],
        [39.9150, 116.4050],
        [39.9155, 116.4070],
        [39.9145, 116.4090],
        [39.9150, 116.4100],
        [39.9140, 116.4120],
        [39.9145, 116.4140],
        [39.9135, 116.4160],
        [39.9140, 116.4180],
        [39.9130, 116.4200],
    ];
    
    // 转换为 Turf 格式
    const turfCoords = complexCoords.map(coord => [coord[1], coord[0]]);
    
    // 将线显示在地图上
    complexLine = L.polyline(complexCoords, {
        color: '#3f51b5',
        weight: 4
    }).bindPopup(`原始线: ${complexCoords.length} 个点`).addTo(map);
    
    currentLayers.push(complexLine);
    
    // 显示每个点
    complexCoords.forEach((coord, i) => {
        const marker = L.circleMarker(coord, {
            color: '#3f51b5',
            radius: 3,
            fillOpacity: 1
        }).bindPopup(`点 ${i+1}`).addTo(map);
        
        currentLayers.push(marker);
    });
    
    // 调整地图视图
    map.fitBounds(complexCoords, { padding: [50, 50] });
    
    // 表单提交事件
    document.getElementById('simplify-form').addEventListener('submit', async function(e) {
        e.preventDefault();
        
        const tolerance = parseFloat(document.getElementById('simplify-tolerance').value);
        const highQuality = document.getElementById('high-quality').value === 'true';
        
        // 转换为 GeoJSON
        const lineGeoJson = {
            type: 'Feature',
            geometry: {
                type: 'LineString',
                coordinates: turfCoords
            },
            properties: {}
        };
        
        try {
            const response = await fetch(`${API_URL}/simplify`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ 
                    geojson: lineGeoJson,
                    tolerance,
                    highQuality
                })
            });
            
            if (!response.ok) {
                throw new Error(`API 请求失败: ${response.status}`);
            }
            
            const data = await response.json();
            showResponse('simplify-panel', data);
            
            // 移除之前的简化线
            currentLayers = currentLayers.filter(layer => {
                if (layer._color === '#ff9800' || layer._color === '#f44336') {
                    map.removeLayer(layer);
                    return false;
                }
                return true;
            });
            
            // 显示简化的线
            if (data.simplified && data.simplified.geometry) {
                const simplifiedCoords = data.simplified.geometry.coordinates.map(coord => [coord[1], coord[0]]);
                
                const simplifiedLine = L.polyline(simplifiedCoords, {
                    color: '#f44336',
                    weight: 3,
                    dashArray: '5, 5'
                }).bindPopup(`简化后: ${simplifiedCoords.length} 个点 (减少了 ${data.stats.reduction})`).addTo(map);
                
                currentLayers.push(simplifiedLine);
                
                // 显示简化后的点
                simplifiedCoords.forEach((coord, i) => {
                    const marker = L.circleMarker(coord, {
                        color: '#f44336',
                        radius: 4,
                        fillOpacity: 1
                    }).bindPopup(`简化后点 ${i+1}`).addTo(map);
                    
                    currentLayers.push(marker);
                });
            }
            
            // 添加图例
            const legend = L.control({ position: 'bottomright' });
            legend.onAdd = function(map) {
                const div = L.DomUtil.create('div', 'legend');
                div.innerHTML = `
                    <div style="background:white;padding:10px;border-radius:5px;border:1px solid #777">
                        <div><span style="display:inline-block;width:20px;height:4px;background:#3f51b5;"></span> 原始线 (${complexCoords.length} 点)</div>
                        <div><span style="display:inline-block;width:20px;height:3px;background:#f44336;margin-top:5px"></span> 简化线 (${data.simplified.geometry.coordinates.length} 点)</div>
                        <div style="margin-top:5px">数据减少: ${data.stats.reduction}</div>
                    </div>
                `;
                return div;
            };
            
            legend.addTo(map);
            currentLayers.push(legend);
            
        } catch (error) {
            handleApiError('simplify-panel', error);
        }
    });
}

// 6. 数据聚类地图设置
let clusterPoints = [];
function setupClusterMap() {
    // 生成随机点
    clusterPoints = [];
    const center = [39.9042, 116.4074]; // 北京市中心
    const pointCount = 30;
    
    for (let i = 0; i < pointCount; i++) {
        // 在中心点周围随机生成点
        const offsetLng = (Math.random() - 0.5) * 0.1;
        const offsetLat = (Math.random() - 0.5) * 0.1;
        
        const pointLng = center[1] + offsetLng;
        const pointLat = center[0] + offsetLat;
        
        clusterPoints.push({
            coordinates: [pointLng, pointLat],
            properties: { id: i, name: `点 ${i+1}` }
        });
        
        // 添加到地图
        const marker = L.circleMarker([pointLat, pointLng], {
            radius: 5,
            fillColor: '#3388ff',
            color: '#3388ff',
            weight: 1,
            opacity: 1,
            fillOpacity: 0.7
        }).bindPopup(`点 ${i+1}`).addTo(map);
        
        currentLayers.push(marker);
    }
    
    // 调整地图视图
    map.fitBounds([
        [center[0] - 0.06, center[1] - 0.06],
        [center[0] + 0.06, center[1] + 0.06]
    ]);
    
    // 表单提交事件
    document.getElementById('cluster-form').addEventListener('submit', async function(e) {
        e.preventDefault();
        
        const numberOfClusters = parseInt(document.getElementById('cluster-count').value);
        
        try {
            const response = await fetch(`${API_URL}/cluster`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ 
                    points: clusterPoints,
                    numberOfClusters
                })
            });
            
            if (!response.ok) {
                throw new Error(`API 请求失败: ${response.status}`);
            }
            
            const data = await response.json();
            showResponse('cluster-panel', data);
            
            // 清除之前的所有点
            clearLayers();
            
            // 定义簇的颜色
            const clusterColors = ['#e53935', '#43a047', '#1e88e5', '#fb8c00', '#8e24aa', '#00acc1', '#ffb300'];
            
            // 处理每个簇
            if (data.clusters) {
                Object.keys(data.clusters).forEach((cluster, index) => {
                    const color = clusterColors[index % clusterColors.length];
                    const points = data.clusters[cluster];
                    
                    // 计算簇中心
                    const coords = points.map(pt => [pt.geometry.coordinates[0], pt.geometry.coordinates[1]]);
                    const multiPoint = turf.multiPoint(coords);
                    const centerPoint = turf.center(multiPoint);
                    
                    // 显示簇中的每个点
                    points.forEach(pt => {
                        const marker = L.circleMarker(
                            [pt.geometry.coordinates[1], pt.geometry.coordinates[0]],
                            {
                                color: color,
                                fillColor: color,
                                radius: 5,
                                weight: 1,
                                opacity: 0.8,
                                fillOpacity: 0.6
                            }
                        ).bindPopup(`${pt.properties.name} (簇 ${cluster})`).addTo(map);
                        
                        currentLayers.push(marker);
                        
                        // 添加线连接到中心
                        const line = L.polyline([
                            [pt.geometry.coordinates[1], pt.geometry.coordinates[0]],
                            [centerPoint.geometry.coordinates[1], centerPoint.geometry.coordinates[0]]
                        ], { 
                            color: color, 
                            weight: 1, 
                            opacity: 0.3,
                            dashArray: '3, 3'
                        }).addTo(map);
                        
                        currentLayers.push(line);
                    });
                    
                    // 显示簇中心
                    const centerMarker = L.circleMarker(
                        [centerPoint.geometry.coordinates[1], centerPoint.geometry.coordinates[0]],
                        {
                            color: 'black',
                            fillColor: color,
                            radius: 8,
                            weight: 2,
                            opacity: 1,
                            fillOpacity: 0.8
                        }
                    ).bindPopup(`簇 ${cluster} 中心 (${points.length} 个点)`).addTo(map);
                    
                    currentLayers.push(centerMarker);
                });
            }
            
        } catch (error) {
            handleApiError('cluster-panel', error);
        }
    });
}

// 7. 多边形合并地图设置
let polygons = [];
function setupUnionMap() {
    // 创建两个多边形
    const poly1Coords = [
        [39.9150, 116.3800],
        [39.9150, 116.4000],
        [39.9000, 116.4000],
        [39.9000, 116.3800],
        [39.9150, 116.3800]
    ];
    
    const poly2Coords = [
        [39.9150, 116.4000],
        [39.9150, 116.4200],
        [39.9000, 116.4200],
        [39.9000, 116.4000],
        [39.9150, 116.4000]
    ];
    
    const poly3Coords = [
        [39.9000, 116.3900],
        [39.9000, 116.4100],
        [39.8900, 116.4100],
        [39.8900, 116.3900],
        [39.9000, 116.3900]
    ];
    
    // 转换为 Turf 格式
    const poly1Turf = poly1Coords.map(coord => [coord[1], coord[0]]);
    const poly2Turf = poly2Coords.map(coord => [coord[1], coord[0]]);
    const poly3Turf = poly3Coords.map(coord => [coord[1], coord[0]]);
    
    polygons = [poly1Turf, poly2Turf, poly3Turf];
    
    // 显示多边形
    const polygon1 = L.polygon(poly1Coords, { 
        color: '#ff5722',
        fillOpacity: 0.4
    }).bindPopup('多边形 1').addTo(map);
    
    const polygon2 = L.polygon(poly2Coords, { 
        color: '#4caf50',
        fillOpacity: 0.4
    }).bindPopup('多边形 2').addTo(map);
    
    const polygon3 = L.polygon(poly3Coords, { 
        color: '#2196f3',
        fillOpacity: 0.4
    }).bindPopup('多边形 3').addTo(map);
    
    currentLayers.push(polygon1, polygon2, polygon3);
    
    // 调整地图视图
    map.fitBounds([
        [39.8900, 116.3800],
        [39.9150, 116.4200]
    ], { padding: [50, 50] });
    
    // 表单提交事件
    document.getElementById('union-form').addEventListener('submit', async function(e) {
        e.preventDefault();
        
        try {
            const response = await fetch(`${API_URL}/union`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ polygons })
            });
            
            if (!response.ok) {
                throw new Error(`API 请求失败: ${response.status}`);
            }
            
            const data = await response.json();
            showResponse('union-panel', data);
            
            // 删除之前的合并多边形
            currentLayers = currentLayers.filter(layer => {
                if (layer._color === '#9c27b0') {
                    map.removeLayer(layer);
                    return false;
                }
                return true;
            });
            
            // 显示合并后的多边形
            if (data.union && data.union.geometry) {
                // 处理可能的多多边形情况
                let unionCoords;
                if (data.union.geometry.type === 'Polygon') {
                    unionCoords = [data.union.geometry.coordinates[0].map(coord => [coord[1], coord[0]])];
                } else if (data.union.geometry.type === 'MultiPolygon') {
                    unionCoords = data.union.geometry.coordinates.map(poly => 
                        poly[0].map(coord => [coord[1], coord[0]])
                    );
                }
                
                unionCoords.forEach((coords, i) => {
                    const unionPolygon = L.polygon(coords, {
                        color: '#9c27b0',
                        fillOpacity: 0.2,
                        weight: 2,
                        dashArray: '5, 5'
                    }).bindPopup('合并后的多边形').addTo(map);
                    
                    currentLayers.push(unionPolygon);
                });
            }
            
        } catch (error) {
            handleApiError('union-panel', error);
        }
    });
}
